<?php
class CircleAction extends Action {
  private $_dev = 0;
  private $_uid = 0;
  private $_username = "";
  private $_checkAction=array("index","group","gourphead",'album','article','diaryview','article_list','huodong');//不检查登录状态的action,"article",
  
  function _initialize() {  
    error_reporting(0);  
    $this->_dev = C("DEV_FLAG");
    $this->assign('dev', $this->_dev);
    $this->_uid = empty($_COOKIE["tpxslmluserid"])?'':$_COOKIE["tpxslmluserid"];
    $this->_username = isset($_COOKIE["tpxslmlusername"])?$_COOKIE["tpxslmlusername"]:'0';
    $this->assign("waitSecond", 1);
    $this->assign("istp", 1);//circle-header2中有TP和PHPWIND都用到，加上这个参数进行区别
    $this->assign("listyle", $_GET["listyle"]?$_GET["listyle"]:1);//用来显示头部的点击当前状态
    if (!in_array(strtolower(ACTION_NAME),$this->_checkAction) && empty($_GET['isAjax'])) {
      if(!$_COOKIE['tpxslmlusername'] || !$_COOKIE['tpxslmluserid'] || !$_COOKIE['tpxslmlgroupid'] || !$_COOKIE['tpxslmlrnd']) {
        $url = "http://localhost/pw8/login.php";
        if ($this->_dev == 0) $url = "http://www.ehs.cn/pw8/login.php";
        $jumpUrl = $url.'?back='.urlencode($_SERVER['REQUEST_URI']);
		//exit($jumpUrl);
		//this->assign("waitSecond",10);
        if(!$this->isAjax()){
		 	$this->assign("jumpUrl", $jumpUrl);
        	$this->error("您还没有登陆，请登录");
          //redirect($url,1,"请登录");
		  }else{
		     $this->ajaxReturn('','请登录后操作',0);
		  }
      }
    }
  }

  public function userInfo(){//返回访问用户的信息
     $user=array('id'=>$this->_uid,'name'=>$this->_username);
	 return $user;
  }

  //截取utf8字符串
  private function utf8Substr($str, $from, $len) {
    return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
      '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
      '$1',$str);
  }

  //检查群组是否存在
  private function _checkGroup($cyid) {
    $this->assign("jumpUrl", "/main/public.php/circle/index/");
    if (!$cyid || $cyid == "") $this->error("请选择群组");
    $m = M("PwColonys");
    $result = $m->where("id = $cyid")->find();
    if($result == "" || !$result) $this->error("请选择群组");
  }

  //判断在群组首页是否显示“我要加入”这个图片
  private function _isShowJoin($cyid) {
    if ($this->_uid == 0) return false;
    $m = M("PwCmembers");
    $result = $m->where("uid = ".$this->_uid." and colonyid = $cyid")->find();
    if (!$result || $result == "" || $result == null) return false;
    return true;
  }

  public function index() {
    //群组列表
    // $list = $this->_getGroupList(array(2,3,4));
    //$this->assign("circle_list", $list);
    
   // dump($list);
    //推荐文章
    $list = $this->_getDiaryList(3);
    $this->assign("tj_list", $list);

    //最新文章
    $list = $this->_getDiaryList(4);
	$diary_ids=array();
	$list2=array();
	foreach($list as $k=>$li){
	  if($li['diary_id'] && !in_array($li['diary_id'],$diary_ids)){
	    $list2[]=$li;
		array_push($diary_ids,$li['diary_id']);
	   }elseif(!$li['diary_id']){
	     $list2[]=$li;
	   }	  
	}
	//dump($diary_ids);
	//echo $m->getLastSQL();
	$this->assign("new_list", $list2);
	
	
	//资深网友
    $zjList = $this->_getZhuanJiaList(5);
    //dump($list);
    foreach($zjList as &$li) {
	  //设置个人介绍默认值
	  if(empty($li['introduce']))
	    $li['introduce']='该用户暂未填写个人介绍';
		
      if(empty($li['icon'])) {//pw8/images/face/none.gif
        $li['icon']= "/pw8/images/face/none.gif";
      }else {
        $icons = explode('|',$li['icon']);
        //$icon = $icons[1]>0 ? "/pw8/attachment/upload/middle/".$icons[0] : "/pw8/images/face/none.gif";
        if(empty($icons[1]))
          $li['icon']= "/pw8/images/face/none.gif";
        else {
          switch($icons[1]) {
            case 1: {
                $li['icon']= "/pw8/images/face/".$icons[0];
              };
              break;//系统头像
            case 2:$li['icon']=$icons[0];
              break;//网络头像
            case 3: {
                 if(count($icons)>4){
				  $icons[0]=str_replace('.gif','.jpg',$icons[0]);
				  $icons[0]=str_replace('.png','.jpg',$icons[0]);
			      $li['icon']="/pw8/attachment/upload/middle/".$icons[0];
			    }
                else
                  $li['icon']="/pw8/attachment/upload/".$icons[0];
              };
              break;//上传头像
          }
        }
      }
    }
	//dump($zjList);
    $this->assign("zj_list", $zjList);
	

    //阅读排行
    $list = $this->_getDiaryList(5);
    $this->assign("hot_list", $list);

    //最新博文
    $m=M('PwDiary');
    $map['privacy']=array('eq','0');
    $list=$m->where($map)->order('postdate DESC')->limit(10)->select();
	$list=$this->_titleIcon($list);
    $this->assign("latestDiary", $list);
	//echo $m->getLastSQL();

    //热门群组	visit
    $list=$this->_getHotGroup();
    $this->assign("hot_group", $list);

    $zhglStr='社会热点关注-企业社会责任-招聘与职业发展';
    $hjbhStr='环境监测与评价-三废治理-给排水工程-ISO14001-清洁生产&CDM-低碳经济';
    $aqscStr='安全评价-安全管理-安全技术-应急管理-OHSAS18001-事故案例';
    $zyjkStr='作业环境管理-个体防护-职业健康监护-工伤与保险-职业病防治-心理健康';
	$diquStr="华北-华东-华南-西部";
	$hyStr="一般制造业-石油天燃气-化学化工-电力-采矿业-建筑业";
    
	$imgNum=1;
    //综合管理群组	visit
    $list=$this->_getGroupList($zhglStr);
    $this->assign("zhglArr", $list);

    //环境保护群组	visit
    $list=$this->_getGroupList($hjbhStr);
    $this->assign("hjbhArr", $list);

    //安全生产群组	visit
    $list=$this->_getGroupList($aqscStr);
    $this->assign("aqscArr", $list);

    //职业健康群组	visit
    $list=$this->_getGroupList($zyjkStr);
    $this->assign("zyjkArr", $list);
	
	//地区群组	visit
    $list=$this->_getGroupList($diquStr);
    $this->assign("diquArr", $list);
	
	//行业群组	visit
    $list=$this->_getGroupList($hyStr);
    $this->assign("hyArr", $list);

    /*//回复排行
    $list = $this->_getDiaryList(6);
    $this->assign("reply_list", $list);*/
    //最新加入成员
    $list = $this->_getNewMembers();
    $this->assign("new_member", $list);
	$this->assign("iconNum",1);
	
	
    $this->display();
  }
  
  
  
  public function article_list(){
    $tables=array('1'=>'APwColonysArticle','2'=>'PwDiary');
	$sort=array('1'=>'create_time','2'=>'postdate');
	
	$type=empty($_GET['type'])?'1':$_GET['type'];
	$title= $type==1?'最新帖子列表':'最新博文列表';
	
	$m=M($tables[$type]);
	$count=$m->count();
	import("@.ORG.Page"); //导入分页类
    
	$page=new Page($count,20);
	
	if($type==1){
		$list=$m->field("a_pw_colonys_article.*,pw_colonys.cname")
		  		->limit("$page->firstRow,$page->listRows")
	      		->order("$sort[$type] DESC")
		 		 ->join("pw_colonys on a_pw_colonys_article.cyid=pw_colonys.id")
		  		->select();
	    foreach($list as &$li){
		    //echo substr($li['create_time'],0,10).'<br>';
			if(substr($li['create_time'],0,10)==date('Y-m-d'))
			 $li['icon']="<img src='/images/new.gif'>";
			else $li['icon']='';
		}			
	}else{
	  $list=$m->limit("$page->firstRow,$page->listRows")
	    	  ->order("$sort[$type] DESC")
			  ->select();
	  foreach($list as &$li){
	          //echo $li['postdate']."<br>";
			if(substr(date('Y-m-d',$li['postdate']),0,10)==date('Y-m-d'))
			 $li['icon']="<img src='/images/new.gif'>";
			else $li['icon']='';
		}		  
   }

	//dump($list);
	//dump($m->getLastSQL());
	
	$this->assign('type',$type);
	$this->assign('title',$title);
	$this->assign('list',$list);
	$this->assign('pages',$page->show());
	$this->display('article-list');
	
  }
  

  /*  社区首页，获取对应的日志列表
   *  params  type:   1-24小时热帖排行  2-本周回帖排行  3-推荐文章  4-最新帖子，5-阅读排行
  */
  public function _getDiaryList($type) {
    $m = M('APwColonysArticle');
    switch($type) {
      case 4:{$list=$m->order('create_time DESC')->limit(10)->select();$list=$this->_titleIcon($list);}//echo $m->getLastSQL();}
        break;
      case 5:{$list=$m->order('read_num DESC')->limit(10)->select();$list=$this->_titleIcon($list);}
        break;
      case 3: {
          $m2 = M('ARecommendPart');
          $part=$m2->where("name='社区_推荐文章'")->find();
          //$m3=M('ARecommend');
          //$ids=$m3->where("part_id={$part['id']}")->limit(5)->select();
          $list=$m->join('a_recommend on a_pw_colonys_article.id=a_recommend.type_id')->where("part_id={$part['id']}")->order("a_recommend.id DESC")->limit(10)->select();
		  $list=$this->_titleIcon($list);
        };
        break;
      default:;
        break;
    }
    return $list;
  }

  private function _getGroupList($str) {
    $names=explode('-',$str);
    //dump($names);
    $list=array();
    foreach($names as $name) {
      $m=M('PwColonys');
      //$item=$m->field('cname')->select();
      //
	  ($item);
      $item=$m->where("cname like '$name%'")->find();
      // echo $m->getLastSQL();
      if($item){
	    $m=D('APwColonysArticle');
		$item['todayArticleNum']=$m->getArticleNum($item['id'],3);
		$item['ArticleNum']=$m->getArticleNum($item['id']);
		$item['ArticleNum2']=$m->getArticleNum($item['id'],2);
	    $list[]=$item;
	   }	  
    }
    return $list;
  }

  //1-头像，2-列表
  private function _getZhuanJiaList($type) {
    $m = M('ARecommendPart');
    $part=$m->where("name='社区_资深网友'")->find();
    $m = M('ARecommend');
    $list=$m->join('pw_members on a_recommend.type_id=pw_members.uid')->where("part_id={$part['id']}")->order("a_recommend.id DESC")->limit($type)->findAll();
	//alert($m->getLastSQL());
    return $list;
  }

  private function _getNewMembers() {
    $m = M('PwCmembers');
    $list=$m->field('username,cname')->join("pw_colonys on pw_cmembers.colonyid=pw_colonys.id")->limit(10)->order('addtime DESC')->select();
    //echo $m->getLastSQL();
    return $list;
  }


  //获取整条线，例如：首页=>社区=>同行业=>环境保护=>DOC专区群
  //目前系统是二级分类
  private function _getGroupLine($cyid) {
    $m = M();
    $sql = "select t1.id as cyid, t1.cname as name, t2.id as style_id, t2.cname as style_name, t3.id as style_up_id, t3.cname as style_up_name
      from pw_colonys t1
      left join pw_cnstyles t2 on (t1.styleid = t2.id)
      left join pw_cnstyles t3 on (t2.upid = t3.id)
      where t1.id = $cyid";
    $result = $m->query($sql);
    return $result[0];
  }
  /*返回热门群组*/
  private function _getHotGroup() {
    $m=M('PwColonys');
    $list=$m->order('visit DESC')->limit(5)->select();
    return $list;

  }

  //某个群组首页
  public function group() {
    $cyid = $_GET["cyid"];
    $this->_checkGroup($cyid);
	
	$tab=empty($_GET['type'])?0:$_GET['type'];
	if(isset($_GET['top']))
	$tab=4;
	
	//dump($_GET);
	//echo $tab;
	$m=M('PwColonys');
	$colony=$m->find($cyid);
	
    //群组文章，包括分页
    $m = M("APwColonysArticle");
    import("@.ORG.Page"); //导入分页类
    $records = 20;//每页多少条记录
    $where = "cyid = $cyid";
    if ($_GET['type'] && $_GET['type'] > 0) $where .= " and type = ".$_GET['type'];
    if ($_GET['top'] && $_GET['top'] > 0) $where .= " and top = ".$_GET['top'];
    $count = $m->where($where)->count();
    $p = new Page ($count,$records);
    $p->setConfig('header','篇记录');
    $p->setConfig('prev',"上一页");
    $p->setConfig('next','下一页');
    $p->setConfig('first','<<');
    $p->setConfig('last','>>');
    $page = $p->show ();
    $list = $m->where($where)->order("top desc,last_comment_time desc,create_time desc")->limit($p->firstRow.",".$p->listRows)->select();
    $ifAdmin = $this->_checkAdmin($this->_uid,$cyid);
	
	$this->assign('colony',$colony);
    $this->assign("count", $count);
    $this->assign("list", $list);
    $this->assign("nowPage",$p->nowPage);
    $this->assign("page", $page );
    $this->assign("records",$records);
    $this->assign("uid",$this->_uid);
    $this->assign("cyid", $cyid);
	$this->assign("tab", $tab);
    $this->assign("type_arr", array(1=>"原创",2=>"转载",3=>"问题"));
    $this->assign("ifAdmin", $ifAdmin);
    //右边栏目显示
    $rightInfo = $this->_getColonysRight($cyid);
    //dump($rightInfo);
    $this->assign("right_info", $rightInfo);
    //判断要不要显示“我要加入”这张图片
    $this->assign("isjoin", $this->_isShowJoin($cyid));
    $this->display();
  }

  //发表群组文章
  public function post() {
   
	
    $cyid = $_GET['cyid'];
	$aid  = empty($_GET['aid'])?0:$_GET['aid'];
	$ifAdmin = $this->_checkAdmin($this->_uid,$cyid);
	
	//检查操作合法性
	$this->_checkUidAndCyid($this->_uid,$cyid);
	
	/*$m=D('PwMembers');
	$isMember=$m->isColonyMember($this->_uid,$cyid);
	if(!$isMember){
	  $this->error('要先加入群组才能在该群组内发表帖子');
	}
	*/
	if($aid){
	 $m=M('APwColonysArticle');
	 $item=$m->find($aid);
	 }else{
	   $item=NULL;
	 }
	 $this->assign("item", $item);
	 $this->assign('aid',$aid);
	
	/*用户博文分类*/
	$m=M('PwDiarytype');
	$dType=$m->where('uid='.$this->_uid)->order('num DESC')->select();
	$this->assign('dtype',$dType);
	 	  
	
    //$this->_checkUidAndCyid($this->_uid, $cyid);
    $m = M("PwColonys");
    $result = $m->where("id = ".$cyid)->find();
    $this->assign("uid", $this->_uid);
    $this->assign('cname', $result["cname"]);
    $this->assign('cyid', $cyid);
    
    $this->assign("ifAdmin", $ifAdmin);
    //右边栏目显示
    $rightInfo = $this->_getColonysRight($cyid);
    $this->assign("right_info", $rightInfo);
    //判断要不要显示“我要加入”这张图片
    $this->assign("isjoin", $this->_isShowJoin($cyid));
    //顶部的个人基本信息和群组，分类等名称
    $top = $this->_getGroupLine($cyid);
    $top["uid"] = $this->_uid;
    $top["username"] = $this->_username;
    $this->assign("top", $top);
    $this->display();
  }

  //检查传过来的用户id和群组id是否正确
  private function _checkUidAndCyid($uid,$cyid) {
//    if ($uid != $this->_uid) {
//      $this->assign("jumpUrl", "/pw8/login.php");
//      $this->error("您还没有登陆，请重新登陆");
//    }
    //检查群组是否存在
    $m = M("PwColonys");
    $result = $m->where("id = $cyid")->find();
    if (!$result || $result == "" || $result == null) {
      $this->assign("jumpUrl", "/main/public.php/circle/index/");
      if(!$this->isAjax())$this->error("请选择您要发表文章的群组");
	  else $this->ajaxReturn('','群组不存在','0');
    }
    //检查用户是否该群组成员
    $m = M("PwCmembers");
    $result = $m->where("uid = $uid and colonyid = $cyid")->find();
    if (!$result || $result == "" || $result == null) {
      $this->assign("jumpUrl", "/main/public.php/circle/group/cyid/$cyid");
      if(!$this->isAjax())$this->error("您不是该组成员，请先加入群组再发表文章");
	  else $this->ajaxReturn('','您不是该组成员，请先加入群组再发表文章','0');
    }
    //return $result;
  }

  /*
  *
  did——日志ID`did` int(10) NOT NULL auto_increment,
  uid——日志所属用户ID `uid` int(10) NOT NULL,
  dtid——日志所属个人分类 `dtid` mediumint(8) NOT NULL,
  aid——附件缓存 `aid` text NOT NULL,
  username——日志所属用户名称 `username` varchar(15) NOT NULL,
  privacy——隐私设置字段，0：全站可见 1：仅好友可见 2:仅自己可见  `privacy` tinyint(1) NOT NULL default '0',
  subject——日志标题 `subject` varchar(150) NOT NULL,
  content——日志内容 `content` text NOT NULL,
  ifcopy——是否允许好友转载 0: 不允许 1：允许  `ifcopy` tinyint(1) NOT NULL default '0',
  copyurl——转载的地址`copyurl` varchar(100) NOT NULL,
  ifconvert——是否转换windcode代码 0：不转换 1：需要转换 2：内容中有windcode，读取的时候需要转换  `ifconvert` tinyint(1) NOT NULL default '0',
  ifwordsfb——记录是否需要进行禁用词替换 值为1-9 如果该值和 db_wordsfb不等，进行替换操作   `ifwordsfb` tinyint(1) NOT NULL default '0', 
  ifupload——是否有附件上传   `ifupload` tinyint(1) NOT NULL default '0',
  r_num——阅读次数 `r_num` int(10) NOT NULL default '0',
  c_num——评论次数   c_num` int(10) NOT NULL default '0',
  postdate——发表日期 `postdate` int(10) NOT NULL default '0',
保存  */
  public function save() {
    $this->_checkUidAndCyid($this->_uid, $_POST['cyid']);
	
    $m = M("APwColonysArticle");
    $time = date("Y-m-d H:i:s");
    $data = array(
      cyid=>$_POST["cyid"],uid=>$_POST["uid"],username=>$this->_username,type=>$_POST['type'],
      title=>$_POST['title'],content=>str_replace('\"','"',$_POST["content"]),create_time=>$time
    );
	
    if($_POST['aid']){
	  $data['id']=$aid=$_POST['aid'];
	  $m->save($data);
	  $opType='编辑';
	 }else{
	   $data['last_comment_time']=date('Y-m-d H:i:s');
       $aid = $m->add($data);
	   //alert($m->getLastSQL());
	   $opType='发表';
	 }
	 
	 //同步文章到个人博文
	if($_POST['toDiary'] || $_POST['aid'])
	  @$this->_toDiary($data,$aid);
	  
	$toURL= __URL__."/article/cyid/".$_POST["cyid"].'/id/'.$aid;
    $this->assign("jumpUrl",$toURL);
    if ($aid> 0) {
      //更新群组文章数目
      $m->query("update pw_colonys set article_num = article_num + 1 where id = ".$_POST["cyid"]);
      //$this->assign('jumpUrl',"/main/public.php?s=/circle/article/cyid/2/id/71");
	  if(!$this->isAjax())$this->success("恭喜！{$opType}发布群组文章成功");
	  else $this->ajaxReturn($toURL,"恭喜！{$opType}发布群组文章成功",'1');
    }else {
      if(!$this->isAjax())$this->success($opType."失败，请重试");
	  else $this->ajaxReturn('',$opType."失败，请重试",'0');
    }
  }

  //具体群组文章页面
  public function article() {
    $id = $_GET['id'];
    //$uid = $_GET["uid"];
    $cyid = $_GET['cyid'];
    $m = M("APwColonysArticle");
    //更新浏览数量
    $m->query("update a_pw_colonys_article set read_num = read_num + 1 where id = $id");
    $article = $m->where("id = $id")->find();
    //回复列表
	
	$diary_id=0;
	if($article['diary_id']){
	    $diary_id=$article['diary_id'];
		$mDiary=M('PwDiary');
		$diary=$mDiary->find($diary_id);
		if($diary){
	     $article['content']='<img src="__ROOT__/Public/Images/loading.gif" />';
		 }else{
		    $diary_id=0;
			$article['content']='很遗憾，该文章由作者在个人博文中转发，原文已被作者删除无法查阅';
		 }
	  }
	
	$isOwner = ($article['uid']==$this->_uid);//文章所有者
	$isLogin = (!empty($this->_uid) && !empty($this->_username));
	//echo $article['uid'].'/'.$this->_uid;
    import("@.ORG.Page"); //导入分页类
    $records = 10;//每页多少条记录
    $n = M("APwColonysArticleComment");
    $where = "aid = $id";
    $count = $n->where($where)->count();
    $p = new Page ($count,$records);
    $p->setConfig('header','篇记录');
    $p->setConfig('prev',"上一页");
    $p->setConfig('next','下一页');
    $p->setConfig('first','<<');
    $p->setConfig('last','>>');
	
    $page = $p->show ();
    $limit = " limit ".$p->firstRow.",".$p->listRows;
    $list = $n->where($where.$limit)->select();
	foreach($list as &$li){
		$li['content']=strip_tags($li['content']);
	}
    //左边栏目显示，个人基本信息
    $article["member_info"] = $this->_getMemberInfo($article["uid"]);
    foreach ($list as $k => $v) {
      $list[$k]["member_info"] = $this->_getMemberInfo($v["uid"]);
    }
    //右边栏目显示
    $rightInfo = $this->_getColonysRight($cyid);
	
	/*当前url*/
    $this->assign("right_info", $rightInfo);
    //判断要不要显示“我要加入”这张图片
    $this->assign("isjoin", $this->_isShowJoin($cyid));
    $ifAdmin = $this->_checkAdmin($this->_uid,$cyid);
    $this->assign("count", $count);
    $this->assign("list", $list);
    $this->assign("nowPage",$p->nowPage);
    $this->assign("page", $page );
    $this->assign("records",$records);
    $this->assign("articl_id", $id);
    $this->assign("uid", $this->_uid);
    $this->assign("username", $this->_username);
    $this->assign("cyid", $cyid);
    $this->assign("article", $article);
	$this->assign('aid',$id);
	$this->assign('diary_id',$diary_id);
    $this->assign("ifAdmin", $ifAdmin);
	$this->assign("isOwner", $isOwner);
	$this->assign("isLogin", $isLogin);
    $this->display();
  }

  //检查管理员
  private function _checkAdmin($uid,$cyid) {
    $m = M();
    $sql = "select ifadmin from pw_cmembers where uid = $uid and colonyid = $cyid";
    $result = $m->query($sql);
    $rt = 0;
    if ($result[0]["ifadmin"] == 1) $rt = 1;
    $sql = "select * from pw_members where uid = $uid";
    $result = $m->query($sql);
    if ($result[0]["groupid"] == 3) $rt = 1;
    return $rt;
  }

  //保存评论
  public function commentSave() {
    $this->_checkUidAndCyid($this->_uid, $_POST['cyid']);
    $m = M("APwColonysArticleComment");
    //更新该文章的评论次数和最后评论信息
    $sql = "update a_pw_colonys_article set comment_num = comment_num+1,last_comment_uid = ".$_POST["uid"].",last_comment_username = '".$_POST["username"]."',last_comment_time='".date("Y-m-d h:i:s")."' where id = ".$_POST["aid"];
    $m->query($sql);
    $_POST['content']=str_replace('\"','"',$_POST['content']);
	$_POST['content']=strip_tags($_POST['content']);
    $result = $m->add($_POST);
    $this->assign("jumpUrl", __URL__."/article/cyid/".$_POST["cyid"]."/id/".$_POST["aid"]);
    if ($result > 0) {
      $this->success("评论成功");
    }else {
      $this->error("评论失败");
    }
  }
  
  
  //删除评论
  public function delComment(){
    if(empty($_GET['cid']) || empty($_GET['cyid'])){
	  $this->ajaxReturn('','参数错误',0);
	}else{
	   if($this->_checkAdmin($this->_uid,$_GET['cyid'])){
	   	$m=M('APwColonysArticleComment');
	   	if($m->where('id='.$_GET['cid'])->delete())
	     $this->ajaxReturn('','删除成功',1);
	    else 
		 $this->ajaxReturn('','删除失败',0);
		}else{
		   $this->ajaxReturn('','权限不足',0);
		}
	} 
	 $this->ajaxReturn('','',1);
  }

  //1-删除文章(包括该文章的所有留言)，2-删除留言(更新评论数量和最后留言人的信息)
  public function del() {
    $type = $_GET["type"];
    $id = $_GET["id"];
    $m = M();
    if ($type == 1) {
      $sql = "delete from a_pw_colonys_article_comment where aid = $id";
      $m->query($sql);
      $sql = "delete from a_pw_colonys_article where id = $id";
      $result = $m->query($sql);
      if (is_array($result)) {
        $this->success("删除成功");
      }else {
        $this->error("删除失败");
      }
    }else if($type == 2) {
      $aid = $m->query("select aid from a_pw_colonys_article_comment where id = $id");
      $aid = $aid[0]["aid"];
      $sql = "delete from a_pw_colonys_article_comment where id = $id";
      $result = $m->query($sql);
      if (is_array($result)) {
        $this->_updateArticleInfo($aid);
        $this->success("删除成功");
      }else {
        $this->error("删除失败");
      }
    }
  }

  //params: $id   a_pw_colonys_article.id
  private function _updateArticleInfo($id) {
    $m = M();
    $sql = "select * from a_pw_colonys_article_comment where aid = $id order by create_time desc limit 0,1";
    $update = $m->query($sql);
    $update = $update[0];
    $sql = "update a_pw_colonys_article set comment_num =comment_num - 1,last_comment_uid = ".$update["uid"].",last_comment_username='".$update["username"]."',last_comment_time='".$update["create_time"]."' where id=$id";
    $m->query($sql);
  }

  /*  获取用户信息，放到群组文章的左边
   *  包括的信息如下：
   *  头像，姓名，性别，出生年月，文章数目，精华数目
  */
  private function _getMemberInfo($uid) {
    $m = M();
    $rt = array();
    $sql = "select * from pw_members where uid = $uid";
    $rt = $m->query($sql);
    $rt = $rt[0];
    $count = $m->query("select count(*) from a_pw_colonys_article where uid = $uid");
    $rt["article_num"] = $count[0]["count(*)"];
    $excellentCount = $m->query("select count(*) from a_pw_colonys_article where uid = $uid and excellent = 1");
    $rt["excellent_num"] = $excellentCount[0]["count(*)"];
    $rt["icon"] = $this->_formatIconSingle($rt["icon"], 1);
    return $rt;
  }

  /*  群组右边信息栏目
   *  包括的信息有：基本信息，管理员，成员，最近访客，成员还喜欢去的群组
   *  基本信息：cname,styleid(=pw_cnstyles.id),members,createtime(积分计算比较复杂，暂时不搞)
   *  管理员：群主pw_colonys.admin，管理员pw_cmembers.ifadmin = 1
   *  成员：pw_cmembers.colonyid = pw_colonys.id  order by addtime
   *  最近访客：pw_colonys.visitor =   a:7:{i:5919;i:1303875175;i:2557;i:1303812366;i:6105;i:1303474333;i:33;i:1303262324;i:3185;i:1302014739;i:5903;i:1300933557;i:1282;i:1300021296;}
   *  成员还喜欢去的群组： order by pw_colonys.visit desc
  */
  private function _getColonysRight($id) {
    $result = array();
    $result["base"] = $this->_getGroupBaseInfo($id);
    $result["manager"] = $this->_getGroupMembers($id,1);
    $result["members"] = $this->_getGroupMembers($id,2);
    $result["visitor"] = $this->_getGroupVisitor($id);
    $result["like"] = $this->_getGroupLike($id);
    return $result;
  }

  //获取群组基本信息
  private function _getGroupBaseInfo($id) {
    $m = M();
    $sql = "select t1.*,t2.cname as style_name
      from pw_colonys t1 left join pw_cnstyles t2 on (t1.styleid = t2.id)
      where t1.id = $id";
    $result = $m->query($sql);
    $result = $result[0];
    $result["cnimg"] = $result["cnimg"]?"http://www.ehs.cn/pw8/attachment/cn_img/".$result["cnimg"]:"http://www.ehs.cn/pw8/images/g/groupnopic.gif";
    return $result;
  }

  //获取群组成员信息    1-管理员，2-所有成员
  private function _getGroupMembers($id,$type) {
    $m = M();
    $sqlAdmin = "";
    $limit = "limit 0,9";
    if ($type == 1) {
      $sqlAdmin = " ifadmin = 1 and ";
      $limit = "limit 0,3";
    }
    $sql = "select count(*) from pw_cmembers where $sqlAdmin colonyid = $id";
    $count = $m->query($sql);
    $result["count"] = $count[0]["count(*)"];
    $sql = "select t1.*,t2.icon from pw_cmembers t1 left join pw_members t2 on (t1.uid = t2.uid) where $sqlAdmin colonyid = $id order by addtime ".$limit;
    $result["list"] = $m->query($sql);
    //if($type!=1)alert($m->getLastSQL());
	//alert($m->getLastSQL());
    $result["list"] = $this->_formatIcon($result["list"],1);
    return $result;
  }

  //获取群组最近访客
  private function _getGroupVisitor($id) {
    $m = M("PwColonys");
    $result = $m->field("visitor")->where("id = $id")->find();
    $resultArr = explode(":", $result["visitor"],3);
    $count = $resultArr[1];
    $vistorStr = preg_replace("/{|}/", "", $resultArr[2]);
    $vistorStr = preg_split("/:|;/", $vistorStr);
    $result = array();
    $result["count"] = $count;
    $vistorIds = array();
    $vistorTimes = array();
    foreach($vistorStr as $k => $v) {
      if ($k > 0 && $k % 4 == 1) $vistorIds[] = $v;
      if ($k > 0 && $k % 4 == 3) $vistorTimes[] = $v;
    }
    $sql = "select * from pw_members where uid in (".implode(",", $vistorIds).")";
    $info = $m->query($sql);
    foreach ($vistorTimes as $key => $value) {
      if ($key > 8) break;//最多显示9个
      foreach ($info as $k => $v) {
        if ($v["uid"] == $vistorIds[$key]) {
          $result["list"][$key] = array(datetime=>$value,uid=>$v["uid"],username=>$v["username"],icon=>$v["icon"]);
          break;
        }
      }
    }
    $result["list"] = $this->_formatIcon($result["list"],1);
    return $result;
  }

  //获取热门群组
  private function _getGroupLike($id) {
    $m = M("PwColonys");
    $rt = $m->where("id = $id")->find();
    $styleID = $rt["styleid"];
    $result = $m->where("styleid = $styleID and id != $id")->order("visit desc")->limit("0,4")->select();
    $result = $this->_formatIcon($result,2);
    return $result;
  }

  //格式化显示的图片  1-用户头像，2-群组照片
  private function _formatIcon($result,$type) {
    if ($type == 1) {
      foreach ($result as $key => $value) {
        $icons = explode('|',$value['icon']);
        if(empty($icons[1]))
          $result[$key]['icon']="/pw8/images/face/none.gif";
        else {
          switch($icons[1]) {
            case 1: {
                $result[$key]['icon']= "/pw8/images/face/".$icons[0];
              };
              break;//系统头像
            case 2:$result[$key]['icon']=$icons[0];
              break;//网络头像
            case 3: {
                if(count($icons)>4){
			      $icons[0]=str_replace('.gif','.jpg',$icons[0]);
			      $result[$key]['icon']="/pw8/attachment/upload/middle/".$icons[0];
			     }
                else
                  $result[$key]['icon']="/pw8/attachment/upload/".$icons[0];
              };
              break;//上传头像
          }
        }
      }
    }else {
      foreach ($result as $key => $value) {
        $result[$key]["cnimg"] = $result[$key]["cnimg"]?"http://www.ehs.cn/pw8/attachment/cn_img/".$result[$key]["cnimg"]:"http://www.ehs.cn/pw8/images/g/groupnopic.gif";
      }
    }
    return $result;
  }

  //格式化显示的图片  1-用户头像，2-群组照片
  private function _formatIconSingle($icon,$type) {
    if ($type == 1) {
      $icons = explode('|',$icon);
      if(empty($icons[1]))
        $icon="/pw8/images/face/none.gif";
      else {
        switch($icons[1]) {
          case 1: {
              $icon= "/pw8/images/face/".$icons[0];
            };
            break;//系统头像
          case 2:$icon=$icons[0];
            break;//网络头像
          case 3: {
              if(count($icons)>4){
			    $icons[0]=str_replace('.gif','.jpg',$icons[0]);
                $icon="/pw8/attachment/upload/middle/".$icons[0];
				}
              else
                $icon="/pw8/attachment/upload/".$icons[0];
            };
            break;//上传头像
        }
      }

    }else {
      $icon = $icon ? "http://www.ehs.cn/pw8/attachment/cn_img/".$icon:"http://www.ehs.cn/pw8/images/g/groupnopic.gif";
    }
    return $icon;
  }

  //文章管理，圈主和管理员的权力
  public function articleManage() {
    $cyid = $_GET["cyid"];
    if ($this->_checkAdmin($this->_uid,$cyid) == 0) $this->error("您没有管理文章的权限");
    import("@.ORG.Page"); //导入分页类
    $records = 10;//每页多少条记录
    $n = M("APwColonysArticle");
    $where = "cyid = $cyid";
    $count = $n->where($where)->count();
    $p = new Page ($count,$records);
    $p->setConfig('header','篇记录');
    $p->setConfig('prev',"上一页");
    $p->setConfig('next','下一页');
    $p->setConfig('first','<<');
    $p->setConfig('last','>>');
    $page = $p->show ();
    $list = $n->where($where)->order("top desc,create_time desc")->limit($p->firstRow.",".$p->listRows)->select();
    $this->assign("count", $count);
    $this->assign("list", $list);
    $this->assign("nowPage",$p->nowPage);
    $this->assign("page", $page );
    $this->assign("records",$records);
    $ifAdmin = $this->_checkAdmin($this->_uid,$_GET['cyid']);
    $this->assign("ifAdmin", $ifAdmin);
    $this->assign("cyid", $cyid);
    //右边栏目显示
    $rightInfo = $this->_getColonysRight($cyid);
    $this->assign("right_info", $rightInfo);
    $this->display("article-manage");
  }

  /*  群管理员操作
   *  1-置顶  2-取消置顶  3-精华  4-取消精华  5-删除
  */
  public function articleOperate() {
    $type = $_POST["type"];
    $ids = $_POST["ids"];
    $m = M();
    $where = " where id in (".implode(",", $ids).")";
    if($type == 5) {
      $sql = "delete from a_pw_colonys_article_comment ".str_replace("id", "aid", $where);
      $result = $m->execute($sql);
      $result === false ? $this->error("操作失败"):"";
      $sql = "delete from a_pw_colonys_article $where";
      $result = $m->execute($sql);
      $result === false ? $this->error("操作失败"):$this->success("操作成功");
    }else {
      $op = array(1=>"top = 1", 2=>"top = 0", 3=>"excellent = 1" ,4=>"excellent = 0");
      $sql = "update a_pw_colonys_article set ".$op[$type].$where;
      $result = $m->execute($sql);
      $result === false ? $this->error("操作失败"):$this->success("操作成功");
    }
  }

  //加入群组
  /*
  *ajax 0=未登录，1=成功，2=已是成员，3=失败
  */
  public function join() {
    $isAjax=empty($_GET['isAjax'])?false:true;
	
    if(!$this->_uid){
	  if(!$isAjax)$this->error("您已经加入该群组");
	  else echo json_encode(array('result'=>0));
	  exit();	  
	}  
	
    $cyid = $_GET["cyid"];
	
    $m = M();
    $sql = "select count(*) from pw_cmembers where colonyid = $cyid and uid = ".$this->_uid;
    $count = $m->query($sql);
    $count = $count[0]["count(*)"];
    $this->assign("jumpUrl", "/main/public.php/circle/group/cyid/$cyid");
    if ($count == 1) {
      if(!$isAjax)$this->error("您已经加入该群组");
	  else echo json_encode(array('result'=>2));
//      $this->ajaxReturn($cyid, "您已经加入该群组了", 2);
    }else {
      $sql = "insert into pw_cmembers (uid,username,colonyid,addtime) values (".$this->_uid.",'".$this->_username."',$cyid,'".time()."')";
      $m->query($sql);
      $sql = "update pw_colonys set members = members + 1 where id = $cyid";
      $m->query($sql);
      if(!$isAjax)$this->success("加入成功");
	   else echo json_encode(array('result'=>1));
//      $this->ajaxReturn($cyid, "加入成功", 1);
    }
  }
  
  /*
  *根据编辑器传过的图片url返回图片的尺寸
  *目前用户无法使用外站图片
  */
  public function getImgSizeAjax(){
     error_reporting(0);
     if(empty($_REQUEST['url']))
       echo json_encode(array('width'=>''));
     else{
       if($arr=getimagesize($_REQUEST['url'])){
          echo json_encode(array('width'=>$arr[0]>600?600:$arr[0]));
		 }else{
		   echo json_encode(array('width'=>''));
		 }  
	  }
  }
  
  
  /*
  *添加好友ajax弹窗
  *待解决问题：黑名单，请求通知
  */
  public function addFriendAjax(){

    if(!$this->_uid){//未登录
	    $status='not_login';
	}else{
	  $uid=$this->_uid;
	  $toid=empty($_GET['uid'])?0:$_GET['uid'];
	  if($uid==$toid){
	    $status='add_myself';
	  }
	  elseif($toid){//正常情况
	     $status='ok';
	     $m=D('PwMembers');
		 $member=$m->getOne($toid);
		 $m=M('PwFriendtype');
		 $teams=$m->where("uid={$uid}")->select();
		 $this->assign('member',$member);
		 $this->assign('friendid',$toid);
		 $this->assign('teams',$teams);
	  }else{//参数错误
	    $status='param_error';
	  }
	}
	//exit($status);
	$this->assign('status',$status);
	$this->display();
  }
  
  /*
  *增加好友分组ajax,0=未登录，1=成功，2=失败,3=请求已发送，4=黑名单，5=已是好友,6=加自己为好友
    return array(
			$this->_sms             => 1,   
			$this->_sms_message     => 100, 
			$this->_sms_rate        => 101, 
			$this->_sms_comment     => 102, 
			$this->_sms_guestbook   => 103, 
			$this->_sms_share       => 104,
			$this->_sms_reply       => 105,
			$this->_notice          => 2,
			$this->_notice_system   => 200,
			$this->_notice_postcate => 201,
			$this->_notice_active   => 202,
			$this->_notice_apps     => 203,
			$this->_request         => 3,
			$this->_request_friend  => 300,
			$this->_request_group   => 301,
			$this->_request_active  => 302,
			$this->_request_apps    => 303,
			$this->_groupsms        => 4,
			$this->_groupsms_colony => 400,
			$this->_groupsms_normal => 401,
			$this->_groupsms_shield => 402,
			$this->_chat            => 5,
			$this->_history         => 0,
		);
		
		var $_sms_message     = 'sms_message';   //短消息
		
		$messageInfo['expand'] = serialize(array('categoryid'=>$categoryId=1,'typeid'=>$typeId=100));
		$messageInfo['extra']  = serialize(array($userName)); //接收者
		
		
  */
  public function addFriendAjaxSubmit(){
     //'好友系统通知：{$L[username]} 请求加您为好友',
	//'[url={$GLOBALS[db_bbsurl]}/u.php?uid={$L[uid]}]{$L[username]}[/url] 请求加您为好友。是否同意？\n\n$L[msg]\n\n',
	//dump($_POST);
    if(!$this->_uid){
	   echo json_encode(array('result'=>0));
	   exit();
	}
	
	if(isset($_POST['type']) && $_POST['type']==1){//添加好友
	   $m=M('PwFriends');
	   $_POST['uid']=$this->_uid;
	   $_POST['descrip']='';
	   $fid=$_POST['friendid'];
	   $check=$m->where("uid={$this->_uid} and friendid={$fid}")->find();
	   if($check){
	     //if($check['status'])
		  echo json_encode(array('result'=>5));//已加为好友
		// else  
		 // echo json_encode(array('result'=>3));//请求已发送
		  exit();
	   }
	     
		 //发送信息
		 $data=array();
		 $data['create_uid']=$this->_uid;
		 $data['create_username']=$this->_username;
		 $data['create_time']=time();
		 $data['expand']='a:2:{s:10:"categoryid";i:3;s:6:"typeid";i:300;}';
		 $data['title']="好友系统通知：{$this->_username} 请求加您为好友";
		 $data['content']="[url=/main/public.php/column/index/uid/{$this->_uid}[/url] 请求加您为好友。是否同意？\n\n{$_POST['content']}\n\n";
		 
		 $m=M('PwMsMessages');
		 if($key=$m->add($data)){
		   //2805,110,7926,3,300,1,0,1307604529,0,1307604529
           //增加消息通知
		   $data=array();
		   $data['uid']=$fid;
		   $data['mid']=$key;
		   $data['categoryid']=3;
		   $data['typeid']=300;
		   $data['status']=1;
		   $data['created_time']=time();
		   $data['modified_time']=time();
		   
		   $m2=M('PwMsRelations');
		   if($m2->add($data)){
		     $m3=M('PwMsConfigs');
			 //$data3['uid']=$fid;
			 //$data3['request_num']
			 $m3->setInc('request_num','uid='.$fid);
			 $m4=M('PwMembers');
			 $m4->save(array('newpm'=>1,'uid'=>$fid));
			 //alert($m3->getLastSQL());
		     echo json_encode(array('result'=>1));
			}
		   else
		     echo json_encode(array('result'=>0));
		 }  
		  else
		   echo json_encode(array('result'=>0));
		//echo $m->getLastSQL();	   
	}elseif($_POST['type']==2){//添加好友分组
	  $data['uid']=$this->_uid;
	  $data['name']=$_POST['name'];
	  $m=M('PwFriendtype');
	  if($key=$m->add($data)){
	    echo json_encode(array('result'=>1,'key'=>$key));
	  }
	  else 
	    echo json_encode(array('result'=>1));
	  //echo $m->getLastSQL();	
	}else{
	  echo json_encode(array('result'=>0));
	}
  }
  
  /*
  *发送消息ajax
  $messageInfo['expand'] = serialize(array('categoryid'=>$categoryId=1,'typeid'=>$typeId=100));
  $messageInfo['extra']  = serialize(array($userName)); //接收者
  */
   public function sendMessageAjax(){
     //dump($_REQUEST);
     if(empty($_POST)){
	   $uid=empty($_GET['uid'])?0:$_GET['uid'];
	   $m=M('PwMembers');
	   $member=$m->find($uid);
	   $this->assign('name',$member['username']);
	   $isLogin=empty($this->_uid)?false:true;
	   $this->assign('isLogin',$isLogin);
	   $this->display();
	 }else{
	    if(empty($this->_uid)){
		  echo json_encode(array('result'=>0));
		  exit();
		}
	   	$data=array();
		$data['create_uid']=$this->_uid;
		$data['create_username']=$this->_username;
		$data['created_time']=time();
		$data['modified_time']=time();
		$data['expand']='a:2:{s:10:"categoryid";i:1;s:6:"typeid";i:100;}';
		$data['extra'] = serialize(array($_POST['name']));
		$data['title']=$_POST['title'];
		$data['content']=$_POST['content'];
		
		$m=M('PwMsMessages');
		if($m->add($data))
		   echo json_encode(array('result'=>1));
		else
		   echo json_encode(array('result'=>2));     
	 }     
   }
   
   /*
   *线下活动模块开始
   */
   public function huodong(){
      $this->assign('uid',$this->_uid);
	  
	  if(file_exists('./PublicFunction/upload/huodong.txt')){
	     $content=file_get_contents('PublicFunction/upload/huodong.txt');	  
		 $lines=array();
		 $content=str_replace("\r\n\r\n",'#',$content);//dump($content);
		 $guys=explode('#',$content);
		 //alert($guys);
		 
		 $lines=array('gz'=>array(),'sh'=>array(),'sz'=>array());
		 //$names=array();
		 foreach($guys as $g){
			//$citys=str_replace("\r\n",'|',$g);
			if(empty($g))continue;
			$cols=explode("\r\n",$g);
			//dump($cols);
			foreach($cols as $city){
			  if(strpos('a'.$city,'城市')){
			    $cname=trim(str_replace('城市:','',$city));
				//echo $cname.' ';
				if($cname=='上海')$cname='sh';
				if($cname=='广州')$cname='gz';
				if($cname=='深圳')$cname='sz';
				}
			  if(strpos('a'.$city,'会员'))
			  $name=trim(str_replace('会员:','',$city));
			  
			}
			//echo $cname.'/'.$name.'<br>';
			//$names[]=$name;
			$lines[$cname][]=$name;
		}
		//alert($lines);
		 if(count($lines)){
			$m=D('PwMembers');
		    foreach($lines as $key=>$li){
			   $users=array();
			   foreach($li as $l){
			     $user=$m->where("username='$l'")->find();
			     if($user)$users[]=$user;
			   }
			   $m->getIconByList(&$users);	
			   $lines[$key]['users']=$users;
			}
		 }
	  }
	  //dump($lines);
	  $this->assign('gzusers',$lines['gz']['users']);
	  $this->assign('szusers',$lines['sz']['users']);
	  $this->assign('shusers',$lines['sh']['users']);
      $this->display();     
   }   
   
   public function huodong_apply(){
     if($this->isAjax()){
	   if(empty($_POST['user_name']) || empty($_POST['real_name']) ||empty($_POST['mobile']) ||empty($_POST['email']) ||empty($_POST['city'])){
	     $this->ajaxReturn('','您填写信息不完成，请填写完整后提交','0');
	   }else{
	     switch($_POST['city']){
		   case 'gz':$city='广州';break;
		   case 'sh':$city='上海';break;
		   case 'sz':$city='深圳';break;
		   default :$city='广州';
		}
		 $str="时间:".date('Y-m-d H:i:s')."\r\n";
	     $str.="会员:".$_POST["user_name"]."\r\n姓名:". $_POST["real_name"]."\r\n手机:".$_POST["mobile"];
		 $str.="\r\n邮箱".$_POST['email']."\r\n电话:".$_POST["phone"];
		 $str.="\r\n城市:".$city."\r\n公司:".$_POST["com"]."\r\n备注:".$_POST["note"]."\r\n\r\n";
	     if(file_put_contents('PublicFunction/upload/huodong.txt',$str,FILE_APPEND)>0)
		    $this->ajaxReturn('','恭喜您，您已经成功报名参加本次活动，最新消息请留言社区帖子或者邮寄通知','1');
		 else 
		    $this->ajaxReturn('','操作失败，请稍候再试','0');
	   }
	 }else{
	    $m=M('PwMembers');
	    $user=$m->find($this->_uid);
	    $this->assign('user',$user);
	    $this->display();	 
	 }   
   }
   
   /*
   *线下活动模块结束
   */  
   
   
   
  /*
  *将发表的群众文章同步到个人博文
  did——日志ID`did` int(10) NOT NULL auto_increment,
  uid——日志所属用户ID `uid` int(10) NOT NULL,
  dtid——日志所属个人分类 `dtid` mediumint(8) NOT NULL,
  aid——附件缓存 `aid` text NOT NULL,
  username——日志所属用户名称 `username` varchar(15) NOT NULL,
  privacy——隐私设置字段，0：全站可见 1：仅好友可见 2:仅自己可见  `privacy` tinyint(1) NOT NULL default '0',
  subject——日志标题 `subject` varchar(150) NOT NULL,
  content——日志内容 `content` text NOT NULL,
  ifcopy——是否允许好友转载 0: 不允许 1：允许  `ifcopy` tinyint(1) NOT NULL default '0',
  copyurl——转载的地址`copyurl` varchar(100) NOT NULL,
  ifconvert——是否转换windcode代码 0：不转换 1：需要转换 2：内容中有windcode，读取的时候需要转换  `ifconvert` tinyint(1) NOT NULL default '0',
  ifwordsfb——记录是否需要进行禁用词替换 值为1-9 如果该值和 db_wordsfb不等，进行替换操作   `ifwordsfb` tinyint(1) NOT NULL default '0', 
  ifupload——是否有附件上传   `ifupload` tinyint(1) NOT NULL default '0',
  r_num——阅读次数 `r_num` int(10) NOT NULL default '0',
  c_num——评论次数   c_num` int(10) NOT NULL default '0',
  postdate——发表日期 `postdate` int(10) NOT NULL default '0',
  保存  */
   private function _toDiary($data,$aid){   
     /*$data = array(
      cyid=>$_POST["cyid"],uid=>$_POST["uid"],username=>$this->_username,type=>$_POST['type'],
      title=>$_POST['title'],content=>str_replace('\"','"',$_POST["content"]),create_time=>$time
    ); */
	//$data['content']=$data['content'];
	$m=M('PwDiary');
	
	if($_POST['diary_id']){//修改博文
	  $data2['did']=$_POST['diary_id'];
	  $data2['subject']=$data['title'];
	  $data2['content']=$data['content'];
	  $m->save($data2);
	 // alert($m->getLastSQL());
	}else{//添加博文
	  $data['dtid']=$_POST['dtid'];
	  $data['subject']=$data['title'];
	  $data['ifcopy']=1;
	  $data['copyurl']='';
	  $data['ifwordsfb']=1;
	  $data['postdate']=time();
	  $diary_id=$m->add($data);
	  //alert($m->getLastSQL());
	  $m=M('APwColonysArticle');
	  $m->save(array('id'=>$aid,'diary_id'=>$diary_id));
	  //alert($m->getLastSQL());
	  $m=M('PwDiarytype');
	  $m->setInc('num','dtid='.$_POST['dtid']);
	}
	//alert($m->getLastSQL());
   }
   
   /*
   *根据文章内容，给文章添加icon
   */
   private function _titleIcon($list){
     foreach($list as &$li){
	    //if(strpos('a'.$li['content'],'<img') || strpos('a'.$li['content'],'[img]'))
		if(strpos('a'.$li['content'],'<embed') || strpos('a'.$li['content'],'[/flash]') || strpos('a'.$li['content'],'[/wmv]'))
		$li['icon']="<img src='__TMPL__images/video-icon.gif' style='margin:0 2px'>";	 
	 }   
	 return $list;
   }
  
  /*
  *
  */
  
  
}
?>
